<?php

class Register extends CI_Controller {

    function __construct() {
        parent::__construct();
        //Load model for inserting into database
        $this->load->model('register_model');

        //Set folder to load view (under View folder)
        $this->layouts->set_view_folder('register');

        //Load libraries
        $this->load->library('formdate');
        $this->load->library('form_validation');

        //load css and js
        $this->layouts->set_css('register/register');
        $this->layouts->set_js('register/jquery.validate');
//        $this->layouts->set_js('validation.js');
        $this->layouts->set_js('register/jquery.pstrength-min.1.2');
        $this->layouts->set_js('validation');


        $formdate = new FormDate();
        $formdate->setLocale('nl_BE');
        $formdate->year['start'] = date('Y');
        $formdate->year['end'] = 1970;
        $formdate->month['values'] = 'numbers';
        if ($this->session->userdata('dob')) {
            $date = $this->session->userdata('dob');
            $dob = explode("-", $date);
            $formdate->year['selected'] = $dob[0];
            $formdate->month['selected'] = $dob[1];
            $formdate->day['selected'] = $dob[2];
        }
        //Send base url to view for processing
        $this->view_data['base_url'] = base_url();
        //Same with $data['base_url'] = base_url();
        $this->view_data['formdate'] = $formdate;
        $this->view_data['country_list'] = $this->register_model->country_list();
    }

    function index() {
        $this->load->library('captcha');
        $expiration = time() - 300; // Two hour limit
        $this->db->query("DELETE FROM captcha WHERE captcha_time < " . $expiration);
        $vals = array(
            //'word'         => 'Random word',
            'img_path' => './assets/img/',
            'img_url' => base_url() . 'assets/img/',
            'font_path' => base_url() . 'system/fonts/texb.ttf',
            'img_width' => '160',
            'img_height' => '60',
            'expiration' => '3600'
        );

        $cap = $this->captcha->create_captcha($vals);
        //
        $this->view_data['image'] = $cap['image'];
        //mette nel db
        $data = array(
            'captcha_id' => '',
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']
        );

        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);
        $this->layouts->view('register_view', $this->view_data);
//        $this->create_user();
    }

    function create_user() {
        /* Setup the validation rules
         * Note: The 1st parameter must be the name of the form input field
         */
        $this->form_validation->set_rules('firstname', 'First Name', 'trim|required|min_length[6]|xss_clean');
        $this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|xss_clean');
//        $this->form_validation->set_rules('postal', 'Postal Code', 'trim|required|numeric|xss_clean');
        $this->form_validation->set_rules('gender', 'Gender', 'trim|required|xss_clean');
        $this->form_validation->set_rules('email', 'Email Address', 'valid_email|trim|required|xss_clean|callback_email_exists');
        $this->form_validation->set_rules('Formdate', 'Date of Birth', 'valid_date|trim|xss_clean|callback_date_check');
        $this->form_validation->set_rules('password1', 'Password', 'trim|required|alpha_numeric|min_length[8]|xss_clean');
        $this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|alpha_numeric|min_length[8]|matches[password1]|xss_clean');
        $this->form_validation->set_rules('captcha', 'Word Verification', 'required|callback_captcha_check');

        if ($this->form_validation->run() == FALSE) {
            $this->index();
        } else {
            //Validation has run and there are no errors, insert into database
            //Create activation code
            $active_code = $this->_random_string(10);

            //Insert into database
            $email = $this->input->post('email');
            $this->register_model->do_register($email, $active_code);

            //Send email confirmation
//            $this->email->from('admin@smartchoice.com', 'Smart Choice Administrator');
//            $this->email->to($email);
//            $this->email->subject('Registration Confirmation');
//            $this->email->message('Please click on this link to complete the registration ' . anchor(base_url() . 'index.php?/register/register_confirm/' . $active_code, 'Confirm Registration'));
//            $this->email->send();
            redirect('visitor/home');

            //Show confirmation message
        }
    }

    function email_exists($email) {
        $this->form_validation->set_message('email_exists', 'This %s already exists. Please choose another email address and try again');

        if ($this->register_model->check_email_exists($email)) {
            //email exists
            return false;
        } else {
            return true;
        }
    }

    //checking the verification word(captca)
    function captcha_check() {
        $this->form_validation->set_message('captcha_check', 'You must enter the word that appears in the image');
        if ($this->register_model->check_captcha_exists()) {
            return true;
        } else {
            return false;
        }
    }

    function _random_string($length) {
        $len = $length;
        $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        $max = strlen($base) - 1;
        $active_code = '';
        mt_srand((double) microtime() * 1000000);
        while (strlen($active_code) < $len + 1) {
            $active_code.=$base{mt_rand(0, $max)};
        }
        return $active_code;
    }

    function register_confirm() {
        $registration_code = $this->uri->segment(3);

        if ($registration_code == '') {
            echo "There is no registration code in the URL";
            exit();
        }

        $registration_confirmed = $this->register_model->confirm_registration($registration_code);

        if ($registration_confirmed) {
            echo "You have successfully registered";
        } else {
            echo "Registration Failed - No record found for that activation code";
        }
    }

//checking the date
    function date_check() {
        if (checkdate($_POST['month'], $_POST['day'], $_POST['year'])) {
            return TRUE;
        } else {
            $this->form_validation->set_message('date_check', 'Correct you Date of Birth.');
            return FALSE;
        }
        if ($_POST['year'] >= 2000) {
            $this->form_validation->set_message('date_check', 'Correct you Date of Birth.');
        }
    }

//Showing profile -- Change Password
    function change_pw() {
//        if (!$this->session->userdata('user_id')) {
//            $uri = site_url('visitor/home');
//            echo "<script>javascript:alert('Please Login to Your Account'); window.location = '" . $uri . "'</script>";
//            exit;
        $this->layouts->view('change_pw', $this->view_data);
    }

    function do_change_pw() {
        $this->register_model->change_pw();
        $uri = site_url('visitor/home');
        echo "<script>javascript:alert('Request Successfully'); window.location = '" . $uri . "'</script>";
    }

    //Forgot password
    function forgot_pw() {
//        if (!$this->session->userdata('user_id')) {
//            $uri = site_url('visitor/home');
//            echo "<script>javascript:alert('Please Login to Your Account'); window.location = '" . $uri . "'</script>";
//            exit;
//        }
        $this->layouts->view('forgot_pw', $this->view_data);
    }

    function do_forgot_pw() {
        $random_pw = $this->_random_string(8);
        $email = $this->input->post('email');
        if ($this->register_model->forgot_pw($email, $random_pw) == FALSE) {
            $uri = site_url('register/forgot_pw');
            echo "<script>javascript:alert('Incorrect Email Address'); window.location = '" . $uri . "'</script>";
        } else {
            $uri = site_url('visitor/home');
            //Send email reset password
            $this->email->from('admin@smartchoice.com', 'Smart Choice Administrator');
            $this->email->to($email);
            $this->email->subject('Reset New Password');
            $this->email->message('Your password has been reset. Please use ' . $random_pw . ' to Login to your account.');
            $this->email->send();
            echo "<script>javascript:alert('Your Password Has Been Reset'); window.location = '" . $uri . "'</script>";
            ;
        }
    }

    //update user profile
    function update_profile() {
//        if (!$this->session->userdata('user_id')) {
//            $uri = site_url('visitor/home');
//            echo "<script>javascript:alert('Please Login to Your Account'); window.location = '" . $uri . "'</script>";
//            exit;
//        }

        $this->layouts->view('update_profile', $this->view_data);
    }

    function do_updateProfile() {
        $this->register_model->do_update_profile();
        $uri = site_url('visitor/home');
        echo "<script>javascript:alert('Update Successfully'); window.location = '" . $uri . "'</script>";
    }

}

?>
